using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace Coriander.Google.Services.Authentication
{
    /// <summary>
    /// Ticket returned from Google authentication service
    /// </summary>
    public class GoogleAuthTicket
    {
        private String auth;
        private String lsid;
        private const String Pattern =
                @"^SID=(?<sid>[A-Za-z0-9_-]+)\r\n" + 
                @"LSID=(?<lsid>[A-Za-z0-9_-]+)\r\n" + 
                @"Auth=(?<auth>[A-Za-z0-9_-]+)\r\n$";
        private String sid;
        private readonly DateTime created;
 
        /// <summary>
        /// Expect value like:
        /// SID=DQAAAGgA...7Zg8CTN\r\nLSID=DQAAAGsA...lk8BBbG\r\nAuth=DQAAAGgA...dk3fA5N
        /// </summary>
        private readonly String rawTicketValue;

        /// <summary>
        /// The Auth part of the ticket
        /// </summary>
        public String Auth
        {
            get { return auth; }
            set { auth = value; }
        }

        /// <summary>
        /// The date and time of creation
        /// </summary>
        public DateTime Created
        {
            get { return created; }
        } 

        /// <summary>
        /// ctor : String
        /// </summary>
        /// <param name="rawTicketValue"></param>
        public GoogleAuthTicket(String rawTicketValue)
        {
            if (Initialize(this.rawTicketValue = rawTicketValue)) 
            {
                created = DateTime.Now;  
            } 
        }

        /// <summary>
        /// Inits
        /// </summary>
        private Boolean Initialize(String rawTicketValue)
        {
            Match match = null;

            if ((match = Regex.Match(rawTicketValue, Pattern)).Success)
            {
                if (match.Captures.Count > 0 && match.Groups.Count > 2)
                {
                    sid = match.Groups["sid"].Value;
                    lsid = match.Groups["lsid"].Value;
                    auth = match.Groups["auth"].Value;
                }

                return true;
            }

            return false;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static Boolean Validate(String value) 
        {
            return Regex.IsMatch(value, Pattern);  
        }
    }
}
